import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { isAuthenticated } from '@/utils/auth'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/about',
    name: 'about',
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/category',
    name: 'category',
    component: () => import(/* webpackChunkName: "category" */ '../views/CategoryView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/fruit',
    name: 'fruit',
    component: () => import(/* webpackChunkName: "fruit" */ '../views/FruitView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/warehouse',
    name: 'warehouse',
    component: () => import(/* webpackChunkName: "warehouse" */ '../views/WarehouseView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/warehouse/:id',
    name: 'warehouse-detail',
    component: () => import(/* webpackChunkName: "warehouse-detail" */ '../views/WarehouseDetailView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../views/LoginView.vue'),
    meta: { guest: true }
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authenticated = isAuthenticated()
  
  // 需要认证的页面
  if (to.meta.requiresAuth && !authenticated) {
    next('/login')
    return
  }
  
  // 游客页面（已登录用户不能访问）
  if (to.meta.guest && authenticated) {
    next('/')
    return
  }
  
  next()
})

export default router
